#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define DEVICE_PATH "/dev/simple_char_device"
#define WRITE_DATA "Hello, simple character device!\n"
#define BUFFER_SIZE 1024

int main()
{
    int fd;
    char read_buffer[BUFFER_SIZE];
    ssize_t bytes_written, bytes_read;

    // 打开字符设备
    fd = open(DEVICE_PATH, O_RDWR);
    if (fd == -1) {
        perror("Failed to open device");
        return 1;
    }

    // 写数据到设备
    bytes_written = write(fd, WRITE_DATA, strlen(WRITE_DATA));
    if (bytes_written == -1) {
        perror("Failed to write data to device");
        close(fd);
        return 1;
    }
    printf("Write %ld bytes to device:%s\n", bytes_written, WRITE_DATA);

    // 移动文件指针到开始位置
    lseek(fd, 0, SEEK_SET);

    // 从设备读取数据
    bytes_read = read(fd, read_buffer, sizeof(read_buffer) - 1);
    if (bytes_read == -1) {
        perror("Failed to read data from device");
        close(fd);
        return 1;
    }

    // 打印读取的数据
    read_buffer[bytes_read] = '\0'; // null-terminate the string
    printf("Read %ld bytes from device: %s\n", bytes_read, read_buffer);

    // 关闭设备
    close(fd);
    return 0;
}

